﻿using NET6.WebAPI.Attributes;
using System.Reflection;

namespace NET6.WebAPI.Extensions
{
    public static class CustomClassExtension
    {
        /// <summary>
        /// 计算对象的信息完整率
        /// </summary>
        /// <typeparam name="T"></typeparam>
        /// <param name="obj">对象</param>
        /// <returns></returns>
        public static double CalculateIntegrityRate<T>(this T? obj) where T : class
        {
            if (obj == null) return 0;

            int totalCount = 0;
            int validCount = 0;

            #region 计算规则
            
            var props = typeof(T).GetProperties();

            foreach (var prop in props) 
            {
                var attr = prop.GetCustomAttribute<IntegrityRateAttribute>();
                if (attr == null) continue;

                totalCount++;

                var val = prop.GetValue(obj).ToStr();
                if (val.HasValue())
                {
                    // 没有自定义规则
                    if (attr.Value == "")
                    {
                        validCount++;
                        continue;
                    }

                    // 有自定义规则
                    if (attr.Value == val)
                    {
                        validCount++;
                    }
                }
            }

            #endregion

            if (totalCount == 0 || validCount == 0) 
            {
                return 0;
            }

            return validCount / totalCount * 100;
        }
    }
}
